<template>
  <div class="submission-management-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>提交记录管理</h2>
      <p>查看和管理学生的论文查重提交记录</p>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="hover">
      <el-form
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        class="search-form"
      >
        <el-form-item label="学生姓名">
          <el-input
            v-model="searchForm.studentName"
            placeholder="请输入学生姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="论文题目">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入论文题目"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="查重类型">
          <el-select
            v-model="searchForm.checkType"
            placeholder="请选择查重类型"
            clearable
            style="width: 150px"
          >
            <el-option label="题目查重" value="title" />
            <el-option label="论文查重" value="paper" />
            <el-option label="信息提取" value="extraction" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险等级">
          <el-select
            v-model="searchForm.riskLevel"
            placeholder="请选择风险等级"
            clearable
            style="width: 150px"
          >
            <el-option label="低风险" value="low" />
            <el-option label="中风险" value="medium" />
            <el-option label="高风险" value="high" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon size="20" color="#409EFF">
            <List />
          </el-icon>
          <span>提交记录列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
            <el-button @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <DataTable
        :data="tableData"
        :columns="tableColumns"
        :loading="tableLoading"
        :pagination="pagination"
        :show-selection="true"
        :show-index="true"
        empty-text="暂无提交记录"
        @page-change="handlePageChange"
        @action="handleTableAction"
        @selection-change="handleSelectionChange"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="提交详情"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生姓名">
            {{ currentDetail.studentName }}
          </el-descriptions-item>
          <el-descriptions-item label="学号">
            {{ currentDetail.studentId }}
          </el-descriptions-item>
          <el-descriptions-item label="论文题目">
            {{ currentDetail.title }}
          </el-descriptions-item>
          <el-descriptions-item label="查重类型">
            <el-tag :type="getCheckTypeTag(currentDetail.checkType)">
              {{ getCheckTypeText(currentDetail.checkType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="重复率">
            <span :class="getSimilarityClass(currentDetail.similarity)">
              {{ currentDetail.similarity }}%
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="风险等级">
            <el-tag :type="getRiskLevelTag(currentDetail.riskLevel)">
              {{ getRiskLevelText(currentDetail.riskLevel) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ formatDateTime(currentDetail.submitTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="查重耗时">
            {{ currentDetail.checkDuration }}秒
          </el-descriptions-item>
        </el-descriptions>

        <!-- 查重结果详情 -->
        <div v-if="currentDetail.detailedResults" class="result-details">
          <h4>查重结果详情</h4>
          <div class="result-list">
            <div
              v-for="(item, index) in currentDetail.detailedResults"
              :key="index"
              class="result-item"
            >
              <div class="similarity-info">
                <el-progress
                  type="circle"
                  :percentage="item.similarity"
                  :width="60"
                  :stroke-width="6"
                  :status="getSimilarityStatus(item.similarity)"
                />
              </div>
              <div class="result-content">
                <p><strong>相似内容：</strong>{{ item.similarText }}</p>
                <p><strong>来源：</strong>{{ item.source }}</p>
                <p><strong>作者：</strong>{{ item.author }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 批量操作对话框 -->
    <el-dialog
      v-model="batchDialogVisible"
      title="批量操作"
      width="500px"
    >
      <div class="batch-content">
        <p>已选择 {{ selectedRows.length }} 条记录</p>
        <el-form :model="batchForm" label-width="100px">
          <el-form-item label="操作类型">
            <el-radio-group v-model="batchForm.action">
              <el-radio label="export">导出选中记录</el-radio>
              <el-radio label="mark_reviewed">标记为已审核</el-radio>
              <el-radio label="send_notification">发送通知</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="batchForm.action === 'send_notification'" label="通知内容">
            <el-input
              v-model="batchForm.message"
              type="textarea"
              :rows="3"
              placeholder="请输入通知内容"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchAction">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  Search,
  Refresh,
  List,
  Download,
  View,
  Edit,
  Delete,
  Message
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '@/stores/app'
import { getSubmissionList, getSubmissionDetail, batchOperation } from '@/api/teacher'
import { formatDateTime } from '@/utils'
import DataTable from '@/components/DataTable.vue'

const appStore = useAppStore()

// 搜索表单
const searchFormRef = ref()
const searchForm = reactive({
  studentName: '',
  title: '',
  checkType: '',
  riskLevel: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const tableLoading = ref(false)
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 选中的行
const selectedRows = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const currentDetail = ref(null)

// 批量操作对话框
const batchDialogVisible = ref(false)
const batchForm = reactive({
  action: 'export',
  message: ''
})

// 表格列配置
const tableColumns = [
  {
    prop: 'studentName',
    label: '学生姓名',
    width: 120,
    fixed: 'left'
  },
  {
    prop: 'studentId',
    label: '学号',
    width: 120
  },
  {
    prop: 'title',
    label: '论文题目',
    minWidth: 200,
    showOverflowTooltip: true
  },
  {
    prop: 'checkType',
    label: '查重类型',
    width: 100,
    type: 'tag',
    tagMap: {
      title: { label: '题目查重', type: 'primary' },
      paper: { label: '论文查重', type: 'success' },
      extraction: { label: '信息提取', type: 'info' }
    }
  },
  {
    prop: 'similarity',
    label: '重复率',
    width: 100,
    formatter: (value) => `${value}%`,
    className: (value) => getSimilarityClass(value)
  },
  {
    prop: 'riskLevel',
    label: '风险等级',
    width: 100,
    type: 'tag',
    tagMap: {
      low: { label: '低风险', type: 'success' },
      medium: { label: '中风险', type: 'warning' },
      high: { label: '高风险', type: 'danger' }
    }
  },
  {
    prop: 'submitTime',
    label: '提交时间',
    width: 180,
    formatter: (value) => formatDateTime(value)
  },
  {
    prop: 'status',
    label: '状态',
    width: 100,
    type: 'tag',
    tagMap: {
      pending: { label: '待审核', type: 'warning' },
      reviewed: { label: '已审核', type: 'success' },
      rejected: { label: '已驳回', type: 'danger' }
    }
  },
  {
    label: '操作',
    width: 200,
    fixed: 'right',
    actions: [
      { key: 'view', label: '查看', type: 'primary', icon: View },
      { key: 'edit', label: '编辑', type: 'default', icon: Edit },
      { key: 'delete', label: '删除', type: 'danger', icon: Delete }
    ]
  }
]

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  if (searchFormRef.value) {
    searchFormRef.value.resetFields()
  }
  pagination.current = 1
  loadData()
}

// 加载数据
const loadData = async () => {
  try {
    tableLoading.value = true
    
    const params = {
      page: pagination.current,
      size: pagination.size,
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === null || params[key] === undefined || params[key] === '') {
        delete params[key]
      }
    })
    
    const result = await getSubmissionList(params)
    tableData.value = result.records
    pagination.total = result.total
    
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  loadData()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.current = page
  loadData()
}

// 表格操作
const handleTableAction = async (actionKey, row) => {
  switch (actionKey) {
    case 'view':
      await showDetail(row.id)
      break
    case 'edit':
      // 编辑操作
      break
    case 'delete':
      await handleDelete(row.id)
      break
  }
}

// 显示详情
const showDetail = async (id) => {
  try {
    const detail = await getSubmissionDetail(id)
    currentDetail.value = detail
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 删除记录
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用删除API
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 导出数据
const handleExport = () => {
  if (selectedRows.value.length > 0) {
    batchForm.action = 'export'
    batchDialogVisible.value = true
  } else {
    ElMessage.warning('请先选择要导出的记录')
  }
}

// 批量操作
const handleBatchAction = async () => {
  try {
    const params = {
      action: batchForm.action,
      ids: selectedRows.value.map(row => row.id),
      message: batchForm.message
    }
    
    await batchOperation(params)
    ElMessage.success('操作成功')
    batchDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('批量操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 获取查重类型标签
const getCheckTypeTag = (type) => {
  const tagMap = {
    title: 'primary',
    paper: 'success',
    extraction: 'info'
  }
  return tagMap[type] || 'default'
}

// 获取查重类型文本
const getCheckTypeText = (type) => {
  const textMap = {
    title: '题目查重',
    paper: '论文查重',
    extraction: '信息提取'
  }
  return textMap[type] || '未知'
}

// 获取相似度样式类
const getSimilarityClass = (similarity) => {
  if (similarity < 15) return 'similarity-low'
  if (similarity < 30) return 'similarity-medium'
  return 'similarity-high'
}

// 获取风险等级标签
const getRiskLevelTag = (level) => {
  const tagMap = {
    low: 'success',
    medium: 'warning',
    high: 'danger'
  }
  return tagMap[level] || 'default'
}

// 获取风险等级文本
const getRiskLevelText = (level) => {
  const textMap = {
    low: '低风险',
    medium: '中风险',
    high: '高风险'
  }
  return textMap[level] || '未知'
}

// 获取相似度状态
const getSimilarityStatus = (similarity) => {
  if (similarity < 15) return 'success'
  if (similarity < 30) return 'warning'
  return 'exception'
}

onMounted(() => {
  appStore.setPageTitle('提交记录管理')
  appStore.setBreadcrumbs([
    { title: '教师管理', path: '/teacher' },
    { title: '提交记录', path: '/teacher/submissions' }
  ])
  
  loadData()
})
</script>

<style scoped>
.submission-management-container {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.header-actions {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

.search-card,
.table-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: none;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.result-details {
  margin-top: 24px;
}

.result-details h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.result-item {
  display: flex;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #F56C6C;
}

.similarity-info {
  flex-shrink: 0;
}

.result-content {
  flex: 1;
  min-width: 0;
}

.result-content p {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.result-content p:last-child {
  margin-bottom: 0;
}

.batch-content p {
  margin: 0 0 16px 0;
  color: #606266;
  font-size: 14px;
}

/* 相似度样式 */
.similarity-low {
  color: #67C23A;
  font-weight: 600;
}

.similarity-medium {
  color: #E6A23C;
  font-weight: 600;
}

.similarity-high {
  color: #F56C6C;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .header-actions {
    margin-left: 0;
    margin-top: 16px;
  }
  
  .result-item {
    flex-direction: column;
    text-align: center;
  }
}
</style>
